﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using CryptoFiles.Data;
using CryptoFiles.Logic;


namespace CryptoFiles.Web
{
    public partial class MyFiles : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

            string errorFile = Request["errorfile"];

            if (errorFile != null)
            {
                lbStatus.ForeColor = Color.Red;
                lbStatus.Text = string.Format("Невозможно скачать файл '{0}'", errorFile);
                lbStatus.Visible = true;
            }

            lbCurrentUser.Text = User.Identity.Name;

            try
            {
                CryptoUser user = new CryptoUser(User.Identity.Name);

                string[] files = user.GetFileList();

                FillTable(files);
            }
            catch(UserNotFoundException)
            {
                FormsAuthentication.SignOut();
                Response.Redirect("Login.aspx");
            }
        }

        protected void btUpload_Click(object sender, EventArgs e)
        {
            CryptoUser user = new CryptoUser(User.Identity.Name);

            if (fileUpload.HasFile)
            {
                byte[] fileContent = fileUpload.FileBytes;

                user.SaveFile(fileUpload.FileName, fileContent);

                lbStatus.Text = string.Format("Файл '{0}' успешно загружен", fileUpload.FileName);
                lbStatus.Visible = true;
                lbStatus.ForeColor = Color.Green;
            }
            else
            {
                lbStatus.Visible = false;
            }

            string[] files = user.GetFileList();
            FillTable(files);
        }


        private void FillTable(IEnumerable<string> files)
        {
            tbFiles.Rows.Clear();

            foreach (var file in files)
            {
                TableRow row = new TableRow();

                TableCell cell =new TableCell();


                string url = "CryptoFile.ashx?file=" + Server.UrlEncode(file);

                cell.Text = string.Format("<a href =\"{0}\">{1}</a>", url, file);

                row.Cells.Add(cell);
                tbFiles.Rows.Add(row);
            }
        }

        protected void btExit_Click(object sender, EventArgs e)
        {
            FormsAuthentication.SignOut();
            Response.Redirect("Login.aspx");
        }
    }
}